<template>
    <div class="sdy-self">
        <sdyHeader title="登录" back></sdyHeader>
        <van-form @submit="submitHandler">
            <van-cell-group inset>
                <van-field
                v-model="username"
                name="用户名"
                label="用户名"
                placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"/>
                <van-field
                v-model="password"
                type="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"/>
                <router-link to="/register">没有账号，请注册!  </router-link>  
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
    </div>
</template>


<script setup lang="ts">
import { ref } from 'vue'
import { loginApi } from '@/api/user'
import { Toast } from 'vant';
import {useRouter , type Router  } from 'vue-router'

//准备两个数据
const username = ref<string>('')
const password = ref<string>('')

const $router:Router =  useRouter()

//提交表单事件
const submitHandler = async ()=>{
    const res = await loginApi(username.value, password.value)
    console.log(res)  //token 和 id 都有了 

    //判断结果
    //表示登录成功
    if(((res as unknown) as {code: string }).code === '200'){
        Toast({
            message:'登录成功',
            icon:'like-o',
        })

        //跳转之前保存 一下 token 和 userid
        window.localStorage.setItem('token' , res.data.token)
        window.localStorage.setItem('user_id' , res.data.userid)

        //跳转到首页
            setTimeout(() =>{
                $router.push({path: '/home'})
                
            },2000)

            return
            }

    //代码执行到这里， 说明手机号不太行 ， 
        Toast({
                message:'登录失败',
                icon:'like-o',
            })

    }
 


</script>

<style scoped lang="scss">


</style>